// CloudPilot 前端应用逻辑

// API 配置
const API_BASE_URL = 'http://localhost:8000/api';

// 全局变量
let currentProvider = null;
let currentRegion = null;
let authToken = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查本地存储的认证信息
    const savedAuth = localStorage.getItem('cloudpilot_auth');
    if (savedAuth) {
        const auth = JSON.parse(savedAuth);
        authToken = auth.token;
        showDashboard();
        loadResources();
    }
    
    // 绑定登录表单事件
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }
    
    // 绑定区域选择器事件
    const regionSelector = document.getElementById('regionSelector');
    if (regionSelector) {
        regionSelector.addEventListener('change', handleRegionChange);
    }
});

// 登录处理
async function handleLogin(e) {
    e.preventDefault();
    
    const provider = document.getElementById('cloudProvider').value;
    const accessKey = document.getElementById('accessKey').value;
    const secretKey = document.getElementById('secretKey').value;
    
    if (!provider || !accessKey || !secretKey) {
        alert('请填写所有必填字段');
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/auth/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                provider,
                access_key: accessKey,
                secret_key: secretKey
            })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            authToken = data.token;
            currentProvider = provider;
            
            // 保存认证信息到本地存储
            localStorage.setItem('cloudpilot_auth', JSON.stringify({
                token: data.token,
                provider: provider
            }));
            
            showDashboard();
            loadResources();
        } else {
            alert(data.detail || '登录失败');
        }
    } catch (error) {
        console.error('登录错误:', error);
        alert('登录失败，请检查网络连接');
    }
}

// 显示仪表盘
function showDashboard() {
    document.getElementById('loginPage').classList.add('d-none');
    document.getElementById('dashboardPage').classList.remove('d-none');
}

// 退出登录
function logout() {
    localStorage.removeItem('cloudpilot_auth');
    authToken = null;
    currentProvider = null;
    currentRegion = null;
    
    document.getElementById('dashboardPage').classList.add('d-none');
    document.getElementById('loginPage').classList.remove('d-none');
    
    // 清空表单
    document.getElementById('loginForm').reset();
}

// 处理区域变更
function handleRegionChange(e) {
    currentRegion = e.target.value;
    loadResources();
}

// 加载资源列表
async function loadResources() {
    if (!authToken) return;
    
    try {
        const params = new URLSearchParams();
        if (currentRegion) {
            params.append('region', currentRegion);
        }
        
        const response = await fetch(`${API_BASE_URL}/resources?${params}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (response.ok) {
            updateResourceStats(data);
            renderResourceCards(data);
        } else {
            console.error('加载资源失败:', data);
        }
    } catch (error) {
        console.error('加载资源错误:', error);
    }
}

// 更新资源统计
function updateResourceStats(data) {
    const stats = {
        ecs: data.ecs?.length || 0,
        oss: data.oss?.length || 0,
        rds: data.rds?.length || 0,
        slb: data.slb?.length || 0
    };
    
    document.getElementById('ecsCount').textContent = stats.ecs;
    document.getElementById('ossCount').textContent = stats.oss;
    document.getElementById('rdsCount').textContent = stats.rds;
    document.getElementById('slbCount').textContent = stats.slb;
}

// 渲染资源卡片
function renderResourceCards(data) {
    const container = document.getElementById('resourceList');
    container.innerHTML = '';
    
    // 渲染 ECS 资源
    if (data.ecs) {
        data.ecs.forEach(ecs => {
            const card = createECSCard(ecs);
            container.appendChild(card);
        });
    }
    
    // 渲染 OSS 资源
    if (data.oss) {
        data.oss.forEach(oss => {
            const card = createOSSCard(oss);
            container.appendChild(card);
        });
    }
    
    // 渲染 RDS 资源
    if (data.rds) {
        data.rds.forEach(rds => {
            const card = createRDSCard(rds);
            container.appendChild(card);
        });
    }
}

// 创建 ECS 卡片
function createECSCard(ecs) {
    const col = document.createElement('div');
    col.className = 'col-lg-4 col-md-6 mb-4';
    
    const statusClass = ecs.status === 'Running' ? 'status-running' : 
                       ecs.status === 'Stopped' ? 'status-stopped' : 'status-pending';
    
    col.innerHTML = `
        <div class="card resource-card" onclick="showMonitor('${ecs.id}')">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-server me-2"></i>
                    ${ecs.name || ecs.id}
                </h6>
            </div>
            <div class="card-body">
                <p class="mb-2">
                    <span class="resource-status ${statusClass}"></span>
                    <strong>状态:</strong> ${ecs.status || '未知'}
                </p>
                <p class="mb-2"><strong>实例类型:</strong> ${ecs.instance_type || '未知'}</p>
                <p class="mb-2"><strong>公网IP:</strong> ${ecs.public_ip || '无'}</p>
                <p class="mb-0"><strong>区域:</strong> ${ecs.region || '未知'}</p>
            </div>
        </div>
    `;
    
    return col;
}

// 创建 OSS 卡片
function createOSSCard(oss) {
    const col = document.createElement('div');
    col.className = 'col-lg-4 col-md-6 mb-4';
    
    col.innerHTML = `
        <div class="card resource-card">
            <div class="card-header bg-success">
                <h6 class="mb-0">
                    <i class="fas fa-hdd me-2"></i>
                    ${oss.name}
                </h6>
            </div>
            <div class="card-body">
                <p class="mb-2"><strong>存储类型:</strong> ${oss.storage_class || '标准'}</p>
                <p class="mb-2"><strong>创建时间:</strong> ${new Date(oss.created_at).toLocaleDateString()}</p>
                <p class="mb-0"><strong>区域:</strong> ${oss.region || '未知'}</p>
            </div>
        </div>
    `;
    
    return col;
}

// 创建 RDS 卡片
function createRDSCard(rds) {
    const col = document.createElement('div');
    col.className = 'col-lg-4 col-md-6 mb-4';
    
    const statusClass = rds.status === 'Running' ? 'status-running' : 'status-stopped';
    
    col.innerHTML = `
        <div class="card resource-card">
            <div class="card-header bg-warning">
                <h6 class="mb-0">
                    <i class="fas fa-database me-2"></i>
                    ${rds.name}
                </h6>
            </div>
            <div class="card-body">
                <p class="mb-2">
                    <span class="resource-status ${statusClass}"></span>
                    <strong>状态:</strong> ${rds.status || '未知'}
                </p>
                <p class="mb-2"><strong>数据库类型:</strong> ${rds.engine || '未知'}</p>
                <p class="mb-2"><strong>版本:</strong> ${rds.engine_version || '未知'}</p>
                <p class="mb-0"><strong>区域:</strong> ${rds.region || '未知'}</p>
            </div>
        </div>
    `;
    
    return col;
}

// 显示监控图表
async function showMonitor(instanceId) {
    const modal = new bootstrap.Modal(document.getElementById('monitorModal'));
    modal.show();
    
    // 加载监控数据
    try {
        const response = await fetch(`${API_BASE_URL}/monitor/${instanceId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (response.ok) {
            renderCharts(data);
        }
    } catch (error) {
        console.error('加载监控数据失败:', error);
    }
}

// 渲染监控图表
function renderCharts(data) {
    const cpuCtx = document.getElementById('cpuChart').getContext('2d');
    const memoryCtx = document.getElementById('memoryChart').getContext('2d');
    const networkCtx = document.getElementById('networkChart').getContext('2d');
    
    // CPU 使用率图表
    new Chart(cpuCtx, {
        type: 'line',
        data: {
            labels: data.cpu.labels,
            datasets: [{
                label: 'CPU 使用率 (%)',
                data: data.cpu.values,
                borderColor: 'rgb(255, 99, 132)',
                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: 'CPU 使用率'
                }
            }
        }
    });
    
    // 内存使用率图表
    new Chart(memoryCtx, {
        type: 'line',
        data: {
            labels: data.memory.labels,
            datasets: [{
                label: '内存使用率 (%)',
                data: data.memory.values,
                borderColor: 'rgb(54, 162, 235)',
                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '内存使用率'
                }
            }
        }
    });
    
    // 网络流量图表
    new Chart(networkCtx, {
        type: 'line',
        data: {
            labels: data.network.labels,
            datasets: [{
                label: '网络流入 (KB/s)',
                data: data.network.in_values,
                borderColor: 'rgb(75, 192, 192)',
                backgroundColor: 'rgba(75, 192, 192, 0.1)',
                tension: 0.1
            }, {
                label: '网络流出 (KB/s)',
                data: data.network.out_values,
                borderColor: 'rgb(255, 159, 64)',
                backgroundColor: 'rgba(255, 159, 64, 0.1)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '网络流量'
                }
            }
        }
    });
}

// 刷新资源
function refreshResources() {
    loadResources();
}

// 工具函数：格式化时间
function formatTime(timestamp) {
    return new Date(timestamp).toLocaleString('zh-CN');
}
